package com.example.boos.stores.myInfo.updateInfo;

import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.bumptech.glide.Glide;
import com.example.boos.HttpUtil.MyPost;
import com.example.boos.MainActivity;
import com.example.boos.R;
import com.example.boos.context.BossInfo;
import com.example.boos.login.login;
import com.example.boos.pojo.Boss;
import com.example.boos.stores.money.balance_main;
import com.example.boos.util.MyCountDownUtil;
import com.example.boos.util.MyThreadPool;
import com.example.boos.util.ShowPopuWIndow;

import java.util.HashMap;
import java.util.Map;

public class updateInfo extends AppCompatActivity {

    private FragmentManager fm;
    private TextView loginOut;
    private ImageView myImage;
    String url = "updateBoss";
    private PopupWindow popupWindow;

    Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 1:
                    Toast.makeText(updateInfo.this, "头像更新失败，请重试！", Toast.LENGTH_SHORT).show();
                    Glide.with(updateInfo.this).load(BossInfo.boss.getImage()).into(myImage);
                    break;
                case 2:
                    TextView myName = (TextView) msg.obj;
                    myName.setText(BossInfo.boss.getBossName());
                    // 更新 sharepreference 中的数据也要更新
                    getSharedPreferences("BossInfo", MODE_PRIVATE).edit().putString("bossName", BossInfo.boss.getBossName()).commit();
                    Toast.makeText(updateInfo.this, "更新成功！", Toast.LENGTH_SHORT).show();
                    break;
                case 3:
                    Toast.makeText(updateInfo.this, "更新失败，请重试！", Toast.LENGTH_SHORT).show();
                    break;
                case 4:
                    // 获取到验证码,验证码倒计时
                    MyCountDownUtil myCountDownUtil = new MyCountDownUtil(60000, 1000, (Button) msg.obj);
                    myCountDownUtil.start();
                    break;
                case 5:
                    // 获取验证码失败
                    Toast.makeText(updateInfo.this, "获取验证码成功", Toast.LENGTH_SHORT).show();
                    break;
                case 6:
                    // 邮箱更新成功
                    // 更新一下页面上的数据
                    TextView myEmail = (TextView) msg.obj;
                    myEmail.setText(BossInfo.boss.getEmail());
                    popupWindow.dismiss();
                    Toast.makeText(updateInfo.this, "邮箱更新成功！", Toast.LENGTH_SHORT).show();
                    break;
                case 7:
                    // 验证码验证失败
                    Toast.makeText(updateInfo.this, "验证码错误", Toast.LENGTH_SHORT).show();
                    break;
                case 8:
                    // 密码更新成功
                    TextView myPwd = (TextView) msg.obj;
                    popupWindow.dismiss();
                    Toast.makeText(updateInfo.this, "密码更新成功！", Toast.LENGTH_SHORT).show();
                    break;
                case 9:
                    // 密码更新失败
                    Toast.makeText(updateInfo.this, "密码更新失败！请重试", Toast.LENGTH_SHORT).show();
                    break;

            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_info);
        // 创建一下
        fm = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fm.beginTransaction();
        updateInfoMainFragment fragment = new updateInfoMainFragment(mainCallBack);
        fragmentTransaction.add(R.id.update_info_fg,fragment);
        //fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commitNow();
        loginOut = findViewById(R.id.loginOut);
        /*退出登录*/
        loginOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences.Editor edit = getSharedPreferences("BossInfo", Context.MODE_PRIVATE).edit();
                edit.clear();
                edit.commit();
                // 跳转到登录页面
                Intent intent = new Intent();
                intent.setComponent(new ComponentName(updateInfo.this, login.class));
                updateInfo.this.startActivity(intent);
            }
        });
    }

    // 菜单
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.back_menu,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        finish();
        return super.onOptionsItemSelected(item);
    }

    // 更新页面里的事件操作
    private updateInfoMainCallBack mainCallBack = new updateInfoMainCallBack() {
        @Override
        public void updateImage(ImageView image) {
            myImage = image;
            ShowPopuWIndow.showPopueWindow(updateInfo.this,1);
        }

        @Override
        public void updatePwd() {
            Map<String, Object> result = ShowPopuWIndow.showPop(R.layout.popue_update_pwd, updateInfo.this);
            View view = (View) result.get("view");
            popupWindow = (PopupWindow) result.get("popWindow");
            EditText oldPwd = view.findViewById(R.id.update_oldPwd);
            EditText newPwd1 = view.findViewById(R.id.update_newPwd);
            EditText newPwd2 = view.findViewById(R.id.update_newPwd2);
            Button ack = view.findViewById(R.id.update_ack);
            Button cancle = view.findViewById(R.id.update_cancle);
            cancle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow.dismiss();
                }
            });
            ack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 修改密码
                    // 先判断原密码是否正确
                    String oldPwdStr = oldPwd.getText().toString();
                    if(oldPwdStr == null || !oldPwdStr.equals(BossInfo.boss.getPassword())){
                        Toast.makeText(updateInfo.this,"请输入正确的原密码！",Toast.LENGTH_SHORT).show();
                        return ;
                    }
                    // 判断新密码是否正确
                    String newPwdStr1 = newPwd1.getText().toString();
                    String newPwdStr2 = newPwd2.getText().toString();
                    if(newPwdStr1 == null || newPwdStr2 == null || newPwdStr1.equals("") || newPwdStr2.equals("")){
                        Toast.makeText(updateInfo.this,"请输入新密码！",Toast.LENGTH_SHORT).show();
                        return ;
                    }
                    if(!newPwdStr1.equals(newPwdStr2)){
                        Toast.makeText(updateInfo.this,"两次输入的密码不一致！",Toast.LENGTH_SHORT).show();
                        return ;
                    }
                    // 检查无误后，开始更新密码
                    MyThreadPool.doJob(new Runnable() {
                        @Override
                        public void run() {
                            Message msg = new Message();
                            Boss boss = new Boss();
                            boss.setId( BossInfo.bossId);
                            boss.setPassword(newPwdStr1);
                            Boolean ack = (Boolean) MyPost.doPost(url,boss);
                            if(ack){
                                // 更新成功
                                BossInfo.boss.setPassword(newPwdStr1);
                                BossInfo.update = 1;
                                getSharedPreferences("BossInfo",MODE_PRIVATE).edit().putString("bossPwd", BossInfo.boss.getPassword()).commit();
                                msg.what = 8;
                            }else{
                                // 更新失败
                                msg.what = 9;
                            }
                            handler.sendMessage(msg);
                        }
                    });
                }
            });
        }

        @Override
        public void updateName(TextView myName) {
            Map<String, Object> result = ShowPopuWIndow.showPop(R.layout.popue_update_name, updateInfo.this);
            View view = (View) result.get("view");
            popupWindow = (PopupWindow) result.get("popWindow");
            Button ack = view.findViewById(R.id.update_ack);
            Button cancle = view.findViewById(R.id.update_cancle);
            EditText editText = view.findViewById(R.id.update_name);
            editText.setText(BossInfo.boss.getBossName());
            cancle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow.dismiss();
                }
            });
            ack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 修改用户名
                    Boss boss = new Boss();
                    boss.setId(BossInfo.bossId);
                    String name = editText.getText().toString();
                    // 可以对name 进行一些判断
                    boss.setBossName(name);
                    popupWindow.dismiss();
                    MyThreadPool.doJob(new Runnable() {
                        @Override
                        public void run() {
                            Message msg = new Message();
                            msg.obj = myName;
                            Boolean ack = (Boolean) MyPost.doPost(url,boss);
                            if(ack){
                                BossInfo.boss.setBossName(name);
                                BossInfo.update = 1;
                                msg.what = 2;
                            }else{
                                msg.what = 3;
                            }
                            handler.sendMessage(msg);
                        }
                    });
                }
            });

        }

        /*
        * 更新邮箱
        * */
        @Override
        public void updateEmail(TextView myEmail) {
            Map<String, Object> result = ShowPopuWIndow.showPop(R.layout.popue_update_email, updateInfo.this);
            View view = (View) result.get("view");
            popupWindow = (PopupWindow) result.get("popWindow");
            Button cancle = view.findViewById(R.id.update_cancle);
            Button ack = view.findViewById(R.id.update_ack);
            Button getCode = view.findViewById(R.id.update_getCode);
            EditText email = view.findViewById(R.id.update_email);
            EditText code = view.findViewById(R.id.update_code);
            cancle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow.dismiss();
                }
            });
            getCode.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String mEmail = email.getText().toString();
                    if(mEmail == null || mEmail.equals("")){
                        Toast.makeText(updateInfo.this,"请输入正确的邮箱！",Toast.LENGTH_SHORT).show();
                        return ;
                    }
                    // 获取验证码操作
                    MyThreadPool.doJob(new Runnable() {
                        @Override
                        public void run() {
                            Message msg = new Message();
                            Boolean isGet = (Boolean) MyPost.doPost("getVerifyCode",mEmail);
                            if(isGet){
                                msg.what = 4; // 成功获取到验证码
                            }else{
                                msg.what = 5;  // 获取失败了
                            }
                            msg.obj = getCode;
                            handler.sendMessage(msg);
                        }
                    });
                }
            });
            ack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 确认修改操作
                    // 先验证验证码
                    MyThreadPool.doJob(new Runnable() {
                        @Override
                        public void run() {
                            String mEmail = email.getText().toString();
                            Map<String,Object> param = new HashMap<>();
                            param.put("email",mEmail);
                            param.put("code",code.getText().toString());
                            Boolean result = (Boolean) MyPost.doPost("userVerifyCode",param);
                            Message msg = new Message();
                            if(result!= null && result){
                                // 验证成功
                                // 更新邮箱
                                Boss boss = new Boss();
                                boss.setId(BossInfo.bossId);
                                boss.setEmail(mEmail);
                                Boolean ack = (Boolean) MyPost.doPost(url,boss);
                                if(ack){
                                    // 邮箱更新成功
                                    msg.what  =6;
                                    BossInfo.update = 1;
                                    msg.obj  = myEmail;
                                    BossInfo.boss.setEmail(mEmail);
                                    getSharedPreferences("BossInfo",MODE_PRIVATE).edit().putString("bossEmail", BossInfo.boss.getEmail()).commit();
                                }
                            }else{
                                // 验证失败
                               msg.what = 7;
                               msg.obj = view;
                            }
                            handler.sendMessage(msg);
                        }
                    });
                }
            });
        }

        @Override
        public void delInfo(View v) {
            // 注销用户
            new AlertDialog.Builder(v.getContext()).setTitle("确认要注销用户？")
                    .setMessage("确认吗？")
                    .setPositiveButton("是", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // 删除用户
                            MyThreadPool.doJob(new Runnable() {
                                @Override
                                public void run() {
                                }
                            });
                        }
                    }).setNegativeButton("否",null).show();

        }


    };



    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            // 如果是 相册返回的话
            if (requestCode == 1 && null != data) {
                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                //获取到图片的本地地址
                final String picturePath = cursor.getString(columnIndex);
                // 显示图片
                //upload(picturePath);
                Glide.with(this).load(picturePath).into(myImage);
                // 记录一下商家信息已经被更新
                BossInfo.update = 1;
              // 更新
                MyThreadPool.doJob(new Runnable() {
                    @Override
                    public void run() {
                        String imageUrl = (String) MyPost.uploadImage("updateBossImage",picturePath, String.valueOf(BossInfo.bossId));
                        if(imageUrl != null && !imageUrl.equals("")){
                            BossInfo.boss.setImage(imageUrl);
                            getSharedPreferences("BossInfo",MODE_PRIVATE).edit().putString("bossImage", BossInfo.boss.getImage()).commit();
                        }else{
                            Message msg = new Message();
                            msg.what = 1;
                        }
                    }
                });
                cursor.close();
            }
        }
    }

}